// 試験環境
document.write(" <script language=javascript src='https://test.ec.nicos.co.jp/token/js/munTokenStg.js' > </script>");
// 本番
//document.write(" <script language=javascript src='https://ec.nicos.co.jp/token/js/munToken.js' > </script>");

// 試験環境
var request_kamei_id = '60004490';
var kamei_id = '60004490';
var kamei_id_ob = '60004490';
var kamei_id_stat = '60012700';
var auth_code = '20006230';
// 本番
//var request_kamei_id = '60014000';
//var kamei_id = '60014000';
//var kamei_id_ob = '60016540';
//var kamei_id_stat = '60042710';
//var auth_code = '00002000';

var cardTimer = "";

$(function() {

    $("[name='cardno']").focus(function(){
        selectCardStart($(this), 'cardkind');
    });

    $("[name='cardno']").blur(function(){
        selectCardEnd($(this), 'cardkind');
    });

});

function selectCardStart(input, hiddenCardType){

    var is_free_chcard = $('input[name="is_free_chcard"]').val();

    cardTimer = setTimeout(function(){
        if ( is_free_chcard )
        {
            selectVmCard(input, hiddenCardType);
        }else{
            selectCard(input, hiddenCardType);
        }
        selectCardStart(input, hiddenCardType);
    }, 1000);
}

function selectCardEnd(input, hiddenCardType){

    var is_free_chcard = $('input[name="is_free_chcard"]').val();

    if ( is_free_chcard )
    {
        selectVmCard(input, hiddenCardType);
    }else{
        selectCard(input, hiddenCardType);
    }
    clearTimeout(cardTimer);
}

function selectCard(input, hiddenCardType){
    var cards = $(".selectCard .card");
    var cardType = $("[name='" + hiddenCardType + "']");
    var val = input.val();

    if(!val){
        cards.removeClass('active disable');
        cardType.val('');
        return;
    }

    // visa
    if ( val.indexOf('4') === 0 ){
        cards.removeClass('active').addClass('disable');
        $(".selectCard .card.visa").removeClass('disable').addClass('active');
        cardType.val('01');
    }

    // master
    else if(val.indexOf('5') === 0){
        cards.removeClass('active').addClass('disable');
        $(".selectCard .card.master").removeClass('disable').addClass('active');
        cardType.val('02');
    }

    // amex
    else if(val.indexOf('34') === 0 || val.indexOf('37') === 0){
        cards.removeClass('active').addClass('disable');
        $(".selectCard .card.amex").removeClass('disable').addClass('active');
        cardType.val('05');
    }

    // jcb
    else if(parseInt(val.substr(0, 4)) >= 3528 && parseInt(val.substr(0, 4)) <= 3589){
        cards.removeClass('active').addClass('disable');
        $(".selectCard .card.jcb").removeClass('disable').addClass('active');
        cardType.val('04');
    }

    // diners
    else if(val.match(/^3{1}[689]{1}/) || val.match(/^3{1}0{1}[0-5]{1}/) ||
        val.indexOf('3095') === 0){

        cards.removeClass('active').addClass('disable');
        $(".selectCard .card.diners").removeClass('disable').addClass('active');
        cardType.val('08');
    }

    // develop
    else if( (val.match(/^9{4}/) || val.match(/^(1234){4}$/))){

        cards.removeClass('active').addClass('disable');
        $(".selectCard .card.visa").removeClass('disable').addClass('active');
        cardType.val('01');
    }

    else {
        cards.removeClass('active disable');
        cardType.val('');
    }

}

function selectVmCard(input, hiddenCardType){
    var cards = $(".selectCard .card");
    var cardType = $("[name='" + hiddenCardType + "']");
    var val = input.val();

    if(!val){
        cards.removeClass('active disable');
        cardType.val('');
        return;
    }

    // visa
    if ( val.indexOf('4') === 0 ){
        cards.removeClass('active').addClass('disable');
        $(".selectCard .card.visa").removeClass('disable').addClass('active');
        cardType.val('01');
    }

    // master
    else if(val.indexOf('5') === 0){
        cards.removeClass('active').addClass('disable');
        $(".selectCard .card.master").removeClass('disable').addClass('active');
        cardType.val('02');
    }

    // develop
    else if( (val.match(/^9{4}/) || val.match(/^(1234){4}$/))){

        cards.removeClass('active').addClass('disable');
        $(".selectCard .card.visa").removeClass('disable').addClass('active');
        cardType.val('01');
    }

    else {
        cards.removeClass('active disable');
        cardType.val('');
    }

}

function card_check(kbn) {
    var cardno = $('input[name="cardno"]').val();
    var secode = $('input[name="securitycode"]').val();
    var validy = $('select[name="cardvalid_y"]').val();
    var validm = $('select[name="cardvalid_m"]').val();
    var cardkind = $('input[name="cardkind"]').val();

    var has_err = 0;

    if (kbn)
    {
        var demand_kbn = $('input[name="demand_kbn"]:checked').val();
        if ( demand_kbn != '60' )
        {
            submit_form_by_action('check');
            return;
        }
    }

    if ( !cardno.length )
    {
        $('#cardno_err').addClass("warn");
        $('#cardno_err').html( "カード番号を入力してください。" );
        has_err = 1;
    }else{
        var rtn = digit_check( cardno );
        if ( rtn == 0 )
        {
            $('#cardno_err').addClass("warn");
            $('#cardno_err').html( "有効なカード番号を入力してください。" );
            has_err = 1;
            var carderr = {
              "cardno_err": "digit_check error: length=" + cardno.length,
            };
            error_print(carderr);
        }
        rtn = chk_prepaid_card( cardno );
        if ( rtn == 1 )
        {
            $('#cardno_err').addClass("warn");
            $('#cardno_err').html( "Ｖプリカ、デビットカード等、クレジットカード以外のカードはご利用いただけません。" );
            has_err = 1;
        }

        if ( !cardkind )
        {
            $('#cardno_err').addClass("warn");
            $('#cardno_err').html( "有効なカード番号を入力してください。" );
            has_err = 1;
            var carderr = {
              "cardno_err": "cardkind error: length=" + cardno.length,
            };
            error_print(carderr);
        }

    }

    if ( !validy || !validm )
    {
        $('#cardvalid_err').addClass("warn");
        $('#cardvalid_err').html( "有効期限を入力してください。" );
        has_err = 1;
    }else{
        rtn = is_valid_cardvalid( validy, validm );
        if ( !rtn )
        {
            $('#cardvalid_err').addClass("warn");
            $('#cardvalid_err').html( "有効期限を正しく入力してください。" );
            has_err = 1;
        }
    }

    if ( !secode )
    {
        $('#securitycode_err').addClass("warn");
        $('#securitycode_err').html( "カード確認番号を入力してください。" );
        has_err = 1;
    }else{
        if ( cardkind == '05' )
        {
            if ( !secode.match(/^\d{4}$/ ) )
            {
                $('#securitycode_err').addClass("warn");
                $('#securitycode_err').html( "カード確認番号が正しくありません。" );
                has_err = 1;
            }
        }else{
            if ( !secode.match(/^\d{3}$/ ) )
            {
                $('#securitycode_err').addClass("warn");
                $('#securitycode_err').html( "カード確認番号が正しくありません。" );
                has_err = 1;
            }
        }

    }

    if ( !has_err )
    {
        nicos_token(1);
    }
}

function digit_check(cardno) {

    var digit_card_list = [
        '1234123412341234',
        '4923200000000000',
        '4923200000000212',
        '4923200000000244',
        '4923200000000261',
        '4923200000000265',
        '4923200000001283',
        '4923200000310000',
        '4923200000310212',
        '4923200000410000',
        '4923200000410212',
        '4923200000610000',
        '4923200000110000',
    ];

    for ( num in digit_card_list )
    {
        if ( cardno == digit_card_list[num] )
        {
            return 1;
        }
    }

    var patrn = /^(9999)(\d{12})$/;
    if ( patrn.exec(cardno) )
    {
        return 1;
    }

    patrn = /^\d{11,16}$/;
    if ( !patrn.exec(cardno) )
    {
        return 0;
    }
}

function chk_prepaid_card(cardno){
    var patrn = /^(406742|42848500|531948|538738)/;
    if ( patrn.exec(cardno) )
    {
        return 1;
    }else{
        return 0;
    }
}

function is_valid_cardvalid(yy,mm){
    if ( !mm.match(/^\d{1,2}$/) || mm < 1 || mm > 12 ) 
    {
        return;
    }
    if ( !yy.match(/^\d{1,2}$/) && !yy.match(/^\d{4}$/) )
    {
        return;
    }

    var myDate = new Date();
    var thisyear = myDate.getFullYear();
    var thismonth = myDate.getMonth()+1;

    if ( yy.length == 2 )
    {
        thisyear = myDate.getYear();
    }

    if ( yy < thisyear || ( yy == thisyear && mm < thismonth ) )
    {
        return;
    }

    return 1;

}


function nicos_token(times) {
    var ec_token= new nicos.ec.token();
    var cardno = $('input[name="cardno"]').val();
    var secode = $('input[name="securitycode"]').val();
    var validy = $("select[name='cardvalid_y'] option:selected").text();
    var validm = $("select[name='cardvalid_m'] option:selected").text();
    var is_free_chcard = $('input[name="is_free_chcard"]').val();

    // 固定値
    var maskpattern = '02';
    var shiharaiop_request = '1';

    var date = new Date();
    var str = "yyyyMMddHHmm";
    str = str.replace(/yyyy|YYYY/, date.getFullYear());
    str = str.replace(/MM/, date.getMonth() >= 9 ? (date.getMonth() + 1) : '0' + (date.getMonth() + 1));
    str = str.replace(/dd|DD/, date.getDate() > 9 ? date.getDate().toString() : '0' + date.getDate());
    str = str.replace(/hh|HH/, date.getHours() > 9 ? date.getHours().toString() : '0' + date.getHours());
    str = str.replace(/mm/, date.getMinutes() > 9 ? date.getMinutes().toString() : '0' + date.getMinutes());

    str= kamei_id+''+auth_code+''+str;

    validm = validm > 9 ? validm : ('0'+validm);
    validy = validy.slice(2,4);
    str="6000449020006230201802091516";
    var asiic='';
    for(i=0;i<str.length;i++){
     asiic += ""+str.charCodeAt(i).toString(16);
    }

    var shaObj = new jsSHA("SHA-256", "HEX");
    shaObj.update(asiic);
    var authcode = shaObj.getHash("B64");
alert(authcode);
    if ( is_free_chcard ) {
        kamei_id = kamei_id_ob;
    }
    if ( times == 2 ) {
        kamei_id = kamei_id_stat;
    }
    
    try {
        ec_token.getTok({
            kamei_id: kamei_id,
            request_kamei_id: request_kamei_id,
            auth_code: authcode,
            card_kaiin_no: cardno,
            card_kakunin_no: secode,
            yuko_mmyy: validm+validy,
            maskpattern: "02",
            shiharaiop_request: "1"
        },function (json){

            if ( json.Result == 0000 )
            {
                if ( times == 1 )
                {
                    setToken(json.token);
                }else if ( times == 2 )
                {
                    setStatToken(json.token);
                }
            }else{
                $('#cardno_err').addClass("warn");
                $('#cardno_err').html( "有効なカード情報を入力してください。" );
                json.kamei_id  = kamei_id;
                json.auth_code = authcode;
                json.request_kamei_id = request_kamei_id;
                error_print(json);
            }
        });

    } catch (e) {
        var carderr = {
            "cardno_err": "getTok() error: message=" + e.message,
        };
        error_print(carderr);
    }
}

function error_print(err){

    var param = {
        "uke_datetime": err.uke_datetime || "",
        "ec_tran_id": err.ec_tran_id || "",
        "Result": err.Result || "",
        "Error_Variable": err.Error_Variable || "",
        "card_kaiin_no_Result": err.card_Result || "",
        "yuko_mmyy_Result": err.yuko_mmyy_Result || "",
        "card_kakunin_no_Result":err.card_kakunin_no_Result || "",
        "masked_card_kaiin_no": err.masked_card_kaiin_no || "",
        "kamei_id": err.kamei_id || "",
        "auth_code": err.auth_code || "",
        "request_kamei_id": err.request_kamei_id || "",
        "cardno_err": err.cardno_err || "",
    };

    $.ajax({
        type: 'GET',
        dataType: 'json',
        async: true,
        url: '/cgi-bin/uss/nicos_card.cgi',
        cache: false,
        data: param,
        success: function(result){
        }
    });

}

function get_conf(){

    var param = {
        "action": "get_conf"
    };

    $.ajax({
        type: 'GET',
        dataType: 'json',
        async: true,
        url: '/cgi-bin/uss/nicos_card.cgi',
        cache: false,
        data: param,
        success: function(result){
            request_kamei_id = result['request_kamei_id'];
            kamei_id = result['kamei_id'];
            kamei_id_ob = result['kamei_id_ob'];
            kamei_id_stat = result['kamei_id_stat'];
            auth_code = result['auth_code'];
        },
        error: function(e, status){

        }
    });

}

function setToken(token){
    var stat   = $('input[name="need_nicos_stat"]').val();
    var cardno = $('input[name="cardno"]').val();

    $('input[name="cardno_token"]').val(token);
    //for TEST
    if( (cardno.match(/^9{4}/) || cardno.match(/^(1234){4}$/))){
        $('input[name="cardno_token"]').val('1234123412341234123412341234123412341234123412341234123412341234');
    }

    if ( stat == 1 )
    {
        nicos_token(2);
    }else{
        submit_form_by_action('check');
    }
}

function setStatToken(token){
    $('input[name="cardno_token_stat"]').val(token);
    submit_form_by_action('check');
}

function submit_form_by_action(action){
    document.getElementsByName('action')[0].value = action;
    document.forms[0].submit();
}